<template>
	<view class="content">
		<view class="padding-top-xl bg-blue"></view>
		<view class="cu-bar bg-blue text-white">
			<view class="action" @tap="back()">
				<text class="cuIcon-back text-white"></text> 返回
			</view>
			<view class="content text-bold">
				{{nick}}
			</view>
		</view>
		<scroll-view scroll-y="true"  :scroll-top="scrollTop">
			<view v-for="(item,index) in msgList" :key="index">
        <view>
          <p>{{item.from}}   {{item.createTime}}</p>
          <text>  {{item.content}}</text>
        </view>
			</view>
		</scroll-view>
		<!-- 发送 -->
		<view class="send">
			<view class="send_box">
				<view class="input"><input type="text" placeholder="请输入要发送的内容" v-model="msgContent" cursor-spacing="10" />
				</view>
				<view class="btn" @tap="send()">发送</view>
			</view>
		</view>

	</view>
</template>

<script>
	var _;
	import IM from "../../components/IM.js/im.js";
  import {formatTimeToStr} from "../../js/date.js";

  export default {
		data() {
			return {
				/*聊天信息*/
				msgList: [],
				/*发送内容*/
        msgContent: '',
				/*scrollHeight*/
				scrollHeight: "10",
				/*标题*/
				title: "",
        nick: "",
        userId: "",
				/*滚动距离*/
				scrollTop: 0,
        //已经加载完所有历史消息
        allHistoryLoaded: false,
			}
		},
		onLoad(e) {
			_ = this;
			this.nick = e.nick
      this.userId = e.userId
      this.getUserChatInfo()
      this.connectSocketInit()
		},
		created() {
			const res = uni.getSystemInfoSync(); //获取手机可使用窗口高度     api为获取系统信息同步接口
			this.scrollHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (300);
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		methods: {
			/*发送消息*/
			send() {
        var createTime = new Date().getTime();

				if (this.msgContent) {
					// 注：只有连接正常打开中，才能正常成功发送消息
          var msg = {
            from: uni.getStorageSync("userid"),
            to: this.userId,
            cmd: 11,
            createTime: createTime,
            chatType: 2,
            msgType: 0,
            content: this.msgContent
          }
          uni.sendSocketMessage({
            data: JSON.stringify(msg), // 这里只能发送消息内容, 在哪里可以自定义事件名
            success: (res) => {
              console.log("消息发送成功", JSON.stringify(res));
              var msg = {};
              msg.from = uni.getStorageSync("userid");
              msg.to = this.userId
              msg.content = this.msgContent
              msg.createTime = formatTimeToStr(new Date(), "yyyy/MM/dd hh:mm:ss")
              this.msgList.push(msg)
              this.msgContent = "";
            },
            fail: (err) => {
              console.log('加入群组的消息通知处理 连接失败重新连接....', err);
            }
          })
					return;
				}
				uni.showToast({
					title: "不允许发送空白信息",
					icon: "none"
				})
			},
      // ws连接初始化
      connectSocketInit() {
        IM.connectSocketInit();
        uni.onSocketError(function (res) {
          uni.showToast({
            title: "WebSocket连接打开失败，请检查！",
            icon: "none"
          })
        });
        this.wsOnSocketMessage()
      },
      //	打开成功监听服务器返回的消息
      wsOnSocketMessage() {
			  let thatMsg = this;
        uni.onSocketMessage(function(res) {
          var data = res.data;
          console.log(data)
          var dataObj = JSON.parse(data);//转换为json对象
          var toUser = uni.getStorageSync("userid")
          if(dataObj.command == 11) {//接收到聊天响应处理;
            var chatObj = dataObj.data;
            var from = chatObj.from;
            if(from == toUser) {
              return;
            }
            var msg = {};
            msg.from = from;
            msg.to = uni.getStorageSync("userid");
            msg.content = chatObj.content;
            msg.createTime = formatTimeToStr(chatObj.createTime, "yyyy/MM/dd hh:mm:ss");
            thatMsg.msgList.push(msg)
          }
        })
      },
			// 关闭websocket
			closeSocket() {
				uni.closeSocket({
					success(res) {
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})

			},
      getUserChatInfo() {
        uni.request({
          url: "http://localhost:8080/im/message/list", //仅为示例，并非真实接口地址。
          method: 'GET',
          data: {
            from: uni.getStorageSync("userid"),
            to: this.userId
          },
          dataType:'json',
          success: (res) => {
            var resdata = res.data
            if (resdata.status == 0) {
              if (resdata.data != null) {
                this.msgList = resdata.data;
              }
            } else {
              uni.showToast({
                title: res.msg,
                icon: "none"
              })
            }

          }
        });
      },
			/*返回*/
			back() {
        this.closeSocket()
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.send {
		background-color: white;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		border-top: 1px solid #dfdfdf;
		padding: 20rpx 20rpx 20rpx 20rpx;

		.send_box {
			display: flex;
			justify-content: space-around;
			align-items: center;

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.input {
			border-bottom: 1px solid #dfdfdf;
			width: 64%;
			padding: 10rpx 0;
		}

		.btn {
			width: 16%;
			background-color: #1D8BF8;
			color: white;
			text-align: center;
			padding: 12rpx 0;
			border-radius: 8rpx;
		}
	}

	.left,
	.right {
		image {
			width: 100rpx;
			height: 100rpx;
		}
	}

</style>
